<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 17-12-15
 * Time: 下午9:25
 */
namespace Home\Controller;
use Think\Controller;

header("Content-type: application/json");
header("Access-Control-Allow-Origin:  *" );
header("Access-Control-Allow-Methods: GET, OPTIONS, POST");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: Content-Type, Content-Length, Accept-Encoding, X-Requested-With, Origin");
class UploadController extends Controller{
    private $uploadReplace =false;
    private $upload_path ="./weiba/upload";

    //自动生成的附件图片类型
    private  $autoFileArr = array(
        '_205_auto',
        '_225_auto',
        '_236_auto',
        '_240_auto',
        '_580_auto',
        '_740_auto',
        '_120_120',
        '_240_240',
        '_260_260',
        '_210_170',
        '_120_170',
        '_100_100',
        '_123_123',
        '_300_310',
        '_46_65',
        '_50_50',
        '_180_255',
        '_660_0',
        '_660_0_120_120',
        '_660_0_240_auto',
        '_360_200',
        '_300_140',
        '_700_380',
        '_236_177',
        '_30_30',
        '_200_200'
    );
    /**
     * 文件上传
     */
    public function upload(){
        $file_seeting = json_decode($_POST['file_seeting'],true);
        $file = $_FILES['file_conente'];
        if(empty($file_seeting) || empty($file)){  exit(json_encode(array('status'=>0,'info'=>'参数错误')));}
        $savePath = $this->upload_path."/".$file_seeting['savepath'];
        // 检查上传目录
        if (!is_dir($savePath)) {
                // 尝试创建目录
                if (!mkdir($savePath, 0777, true)) {
                    exit(json_encode(array('status'=>0,'info'=>'目录不存在或者创建失败')));
                }
        } else {
            if (!is_writeable($savePath)) {
                exit(json_encode(array('status'=>0,'info'=>'目录不可写')));
            }
        }
        $file_save_arr['savepath'] = $savePath;
        $file_save_arr['savename'] = $file_seeting['savename'];
        $file_save_arr['tmp_name'] = $file['tmp_name'];
        if($this->save($file_save_arr)){
            exit(json_encode(array('status'=>1,'info'=>'上传成功')));
        }else{
            exit(json_encode(array('status'=>0,'info'=>'上传失败')));
        }
    }

    /**
    +----------------------------------------------------------
     * 上传一个文件
    +----------------------------------------------------------
     * @access public
    +----------------------------------------------------------
     * @param mixed $name 数据
     * @param string $value  数据表名
    +----------------------------------------------------------
     * @return string
    +----------------------------------------------------------
     * @throws ThinkExecption
    +----------------------------------------------------------
     */
    private function save($file)
    {
        $filename = $file['savepath'].$file['savename'];
        if (!$this->uploadReplace && is_file($filename)) {
            return false;
        }
        $saveFileName = $this->auto_charset($filename, 'utf-8', 'gbk');
        if (!move_uploaded_file($file['tmp_name'], $saveFileName)) {
            return false;
        }
        return true;
    }


    // 自动转换字符集 支持数组转换
   private  function auto_charset($fContents, $from, $to)
    {
        $from   =  strtoupper($from)=='UTF8'? 'utf-8':$from;
        $to       =  strtoupper($to)=='UTF8'? 'utf-8':$to;
        if (strtoupper($from) === strtoupper($to) || empty($fContents) || (is_scalar($fContents) && !is_string($fContents))) {
            //如果编码相同或者非字符串标量则不转换
            return $fContents;
        }
        if (is_string($fContents)) {
            if (function_exists('iconv')) {
                return iconv($from, $to, $fContents);
            } else {
                return $fContents;
            }
        } elseif (is_array($fContents)) {
            foreach ($fContents as $key => $val) {
                $_key =     auto_charset($key, $from, $to);
                $fContents[$_key] = auto_charset($val, $from, $to);
                if ($key != $_key) {
                    unset($fContents[$key]);
                }
            }
            return $fContents;
        } else {
            return $fContents;
        }
    }

    /**
     * 生成缩略图
     */
    public function thumb(){
        $file_seeting = json_decode($_POST['file_seeting'],true);
        $file = $_POST['file_conente'];
        if(empty($file_seeting))
        exit(json_encode(array('status'=>0,'info'=>'配置为空')));
        if(empty($file))
        exit(json_encode(array('status'=>0,'info'=>'文件路径不能为空')));

        
        $filename  = $this->upload_path.$file;
        $info      = pathinfo($filename);
        $replace = $cut =false;$width = $file_seeting['width'];$height = $file_seeting['height'];

        $oldFile   = $info['dirname'].DIRECTORY_SEPARATOR.$info['filename'].'.'.$info['extension'];
        $thumbFile = $info['dirname'].DIRECTORY_SEPARATOR.$info['filename'].'_'.$width.'_'.$height.'.'.$info['extension'];
        $oldFile = str_replace('\\', '/', $oldFile);
        $thumbFile = str_replace('\\', '/', $thumbFile);
        //exit(json_encode(array('status'=>1,'info'=>$oldFile)));
        //原图不存在直接返回
        if (!file_exists($oldFile)) {
            @unlink($thumbFile);
            exit(json_encode(array('status'=>0,'info'=>"原图不存在")));
            //缩图已存在并且 replace替换为false
        } elseif (file_exists($thumbFile) && !$replace) {
            exit(json_encode(array('status'=>1,'info'=>str_replace('./weiba/upload','',$thumbFile))));
            //执行缩图操作
        } else {
            $oldimageinfo     = getimagesize($oldFile);
            $old_image_width  = intval($oldimageinfo[0]);
            $old_image_height = intval($oldimageinfo[1]);
            if ($old_image_width<=$width && $old_image_height<=$height) {
                @unlink($thumbFile);
                @copy($oldFile,$thumbFile);
                exit(json_encode(array('status'=>1,'info'=>str_replace('./weiba/upload','',$thumbFile))));
            } else {
                //生成缩略图
                if ($height=="auto") {
                    $height=0;
                }
                import("Vendor.phpthumb.ThumbLib");
                $thumbLib = new \PhpThumbFactory();
                $thumb = $thumbLib::create($filename);
                if ($cut) {
                    $thumb->adaptiveResize($width, $height);
                } else {
                    $thumb->resize($width, $height);
                }
                $res = $thumb->save($thumbFile);
                //缩图失败
                if (!$res) {
                    $thumbFile = $oldFile;
                }
                exit(json_encode(array('status'=>1,'info'=>str_replace('./weiba/upload','',$thumbFile))));
            }
        }

    }

    /**
     * 删除文件
     */
    public function delete(){
        $file = $_POST['file_conente'];
        if(!$file){exit(json_encode(array('status'=>0,'info'=>'数据出错')));}
        if(file_exists($this->upload_path.$file)){//文件是否存在
            @unlink ($this->upload_path.$file);
            //删除各种自动生成的文件
            $auto = explode('.',$file);
            $a_file_dir = $this->upload_path.$auto[0];
            foreach($this->autoFileArr as $val){
                $a_file = $a_file_dir.$val.'.'.$auto[1];//自动生成的文件
                if(file_exists($a_file)){//自动生成的文件是否存在
                    @unlink ($a_file);
                }
            }
        }
        $this->rm_empty_dir($this->upload_path);
        exit(json_encode(array('status'=>1,'info'=>'')));
    }

    /** 删除所有空目录
     * @param String $path 目录路径
     */
   private  function rm_empty_dir($path){
        if(is_dir($path) && ($handle = opendir($path))!==false){
            while(($file=readdir($handle))!==false){// 遍历文件夹
                if($file!='.' && $file!='..'){
                    $curfile = $path.'/'.$file;// 当前目录
                    if(is_dir($curfile)){// 目录
                        $this->rm_empty_dir($curfile);// 如果是目录则继续遍历
                        if(count(scandir($curfile))==2){//目录为空,=2是因为.和..存在
                            rmdir($curfile);// 删除空目录
                        }
                    }
                }
            }
            closedir($handle);
            return true;
        }else{
            return false;
        }
    }

    /**
     * 检测某个文件是否存在
     */
    public function read(){
        $file = $_POST['file_conente'];
        if(!$file){exit(json_encode(array('status'=>0,'info'=>'数据出错')));}
        if(file_exists($this->upload_path.$file)){//文件是否存在
            exit(json_encode(array('status'=>1,'info'=>'')));
        }else{
            exit(json_encode(array('status'=>0,'info'=>'文件不存在')));
        }
    }

    /**
     * 头像生成方法
     */
    public function avatar(){
       // exit(json_encode(array('status'=>1,'info'=>$_POST['file_conente'])));
        $file_seeting = json_decode($_POST['file_seeting'],true);
        $file = $_POST['file_conente'];
        if(empty($file_seeting))
            exit(json_encode(array('status'=>0,'info'=>'配置为空')));
        if(empty($file))
            exit(json_encode(array('status'=>0,'info'=>'文件路径不能为空')));
        import("Vendor.phpthumb.ThumbLib");
        $thumbLib = new \PhpThumbFactory();
        $src = $this->upload_path.'/'.$_POST['file_conente'];
        $thumb = $thumbLib::create($src);
        $res = $thumb->crop($file_seeting['x1'], $file_seeting['y1'], $file_seeting['w'], $file_seeting['h']);
        //获取获取缩图后的数据
        if (!$res) {
            exit(json_encode(array('status' => 0, 'info' => '头像切割失败')));
        }
        if (!file_exists($this->upload_path . $file_seeting['savepath'].$file_seeting['savename'])) {
            // 检查上传目录
            if (!is_dir($this->upload_path . $file_seeting['savepath'])) {
                // 尝试创建目录
                if (!mkdir($this->upload_path . $file_seeting['savepath'], 0777, true)) {
                    exit(json_encode(array('status'=>0,'info'=>'目录不存在或者创建失败')));
                }
            } else {
                if (!is_writeable($this->upload_path . $file_seeting['savepath'])) {
                    exit(json_encode(array('status'=>0,'info'=>'目录不可写')));
                }
            }
        }
        $thumb->save($this->upload_path . $file_seeting['savepath'].$file_seeting['savename'], 'jpg');
        exit(json_encode(array('status'=>1,'info'=>'')));
    }

     //第三方自动登录头像处理
    public function autoAvatar(){
    	$file_seeting = json_decode($_POST['file_seeting'],true);
        $file = $_POST['file_conente'];
        if(empty($file_seeting) || empty($file)){  exit(json_encode(array('status'=>0,'info'=>'参数错误')));}
        $savePath = $this->upload_path."/".$file_seeting['savepath'];
        // 检查上传目录
        if (!is_dir($savePath)) {
                // 尝试创建目录
                if (!mkdir($savePath, 0777, true)) {
                    exit(json_encode(array('status'=>0,'info'=>'目录不存在或者创建失败')));
                }
        } else {
            if (!is_writeable($savePath)) {
                exit(json_encode(array('status'=>0,'info'=>'目录不可写')));
            }
        }


         $opts = array(
            'http' => array(
                'method' => "GET",
                'timeout' => 3, //超时30秒
                'user_agent' => "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
            )
        );
        $context = stream_context_create($opts);
        $imageData = file_get_contents($file, false, $context);
         if (!file_put_contents($savePath.'/'.$file_seeting['savename'], $imageData)) {
               exit(json_encode(array('status'=>0,'info'=>'上传失败')));
            }else{
            	 exit(json_encode(array('status'=>1,'info'=>'上传成功')));
            }
    }

}